using IM.Easy.Infrastructure.Query;
using Microsoft.AspNetCore.Mvc;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;
using IM.Easy.Entity.System;
using Microsoft.AspNetCore.Mvc.Controllers;
using System.Reflection;
using IM.Easy.Core.Cache;
using System.Security.Cryptography;
using IM.Easy.Core.Attributes;
using IM.Easy.Core.Result;
using IM.Easy.SystemServices.Services;
using EndpointManagement;
using IM.Easy.Core.Filters;
using IM.Easy.Core.Utils;

namespace IM.Easy.Api.Controllers.System
{
    /// <summary>
    /// ApiPermissionsController 控制器
    /// </summary>
    public class ApiPermissionsController : ControllerBase
    {
        private readonly IApiPermissionsService _service;

        /// <summary>
        /// 构造函数，注入服务
        /// </summary>
        /// <param name="service">服务接口</param>
        public ApiPermissionsController(IApiPermissionsService service)
        {
            _service = service;
        }

        /// <summary>
        /// 获取所有ApiPermissions对象
        /// </summary>
        /// <returns>返回ApiPermissions列表</returns>
        [HttpGet]
        [Api(Name = "接口明细", Perm = "api:perm:list", Required = true)]
        public PageResponse<ApiPermissions> GetList([FromQuery] ApiPermissionsQueryDto query)
        {
            return _service.GetPageList(query);
        }

        /// <summary>
        /// 根据ID获取ApiPermissions对象
        /// </summary>
        /// <param name="id">对象的ID</param>
        /// <returns>返回指定的ApiPermissions对象</returns>
        [HttpGet("{id}")]
        [Api(Name = "接口明细", Perm = "api:perm:info", Required = true)]
        public ApiPermissions GetById([FromRoute] long id)
        {
            var result = _service.GetById(id);
            return result ?? throw new KeyNotFoundException($"未找到ID为 {id} 的ApiPermissions对象。");
        }

        /// <summary>
        /// 更新现有的ApiPermissions对象
        /// </summary>
        /// <param name="id">对象的ID</param>
        /// <param name="entity">更新后的ApiPermissions对象</param>
        [HttpPut]
        [Api(Name = "修改接口", Perm = "api:perm:put", Required = true)]
        public void Update([FromBody] ApiPermissions entity)
        {
            _service.Update(entity);
            EndPointManager.UpdateOrAdd(entity);
        }

        /// <summary>
        /// 同步现有接口
        /// </summary>
        [Api(Name = "同步接口", Perm = "api:perm:sync", Required = true)]
        public void PutSync([FromBody] DiffApiPermissions diff)
        {
            //同步前校验
            if (diff.Added.Count > 0)
            {
                foreach (var item in diff.Added)
                {
                    if (!_service.Validate(item, out string msg))
                    {
                        ExceptionUtils.ThrowBusinessException(msg);
                        break;
                    }
                    ;
                }
            }

            _service.InsertRange(diff.Added);
            _service.Delete(diff.Deleted);
            //同步后，所有接口全部重新加载
            EndPointManager.Clear();
            var list = _service.GetList();
            EndPointManager.Register(list);
        }

        /// <summary>
        /// 获取选项下拉框----->从数据库中获取数据
        /// </summary>
        /// <returns></returns>
        [Api(Name = "获取接口下拉列表", Perm = "api:perm:option", Required = true)]
        public List<ApiPermissions> GetOption([FromQuery] string keyword)
        {
            List<ApiPermissions> list = _service.GetOptionList(keyword);
            return list;
        }

        /// <summary>
        /// 获取接口差异信息
        /// </summary>
        [Api(Name = "获取差异接口数据", Perm = "api:perm:diff", Required = true)]
        public DiffApiPermissions GetDiff()
        {
            var endpoints = _service.ScanEndpoint();
            var apiPermissions = _service.Convert(endpoints);
            var old = _service.GetList();
            var diff = _service.Diff(apiPermissions, old);
            return diff;
        }

        /// <summary>
        /// 修改接口状态
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Api(Name = "修改接口状态", Perm = "api:perm:bulk:status", Required = true)]
        [HttpPut("bulk/status")]
        public BlukResult BulkStatus([FromBody] BlukStatus data)
        {
            var blukResult = new BlukResult();
            foreach (var item in data.Ids)
            {
                try
                {
                    var endpoint = _service.GetById(item);
                    var count = _service.SetStatus(data.Status, item);
                    endpoint.IsEnabled = data.Status;
                    EndPointManager.UpdateOrAdd(endpoint);
                    blukResult.AddSuccess();
                }
                catch (Exception)
                {
                    blukResult.AddFailure(item, $"id为{item}的数据修改状态失败");
                    continue;
                }
            }
            if (blukResult.FailureCount > 0)        //如果上面失败，则采用补偿机制（所有接口全部重新加载）
            {
                EndPointManager.Clear();
                var list = _service.GetList();
                EndPointManager.Register(list);
            }

            return blukResult;
        }

        /// <summary>
        /// 开启或关闭日志记录
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Api(Name = "修改接口日志开关", Perm = "api:perm:bulk:track", Required = true)]
        [HttpPut("bulk/trackStatus")]
        public BlukResult BulkLogTrack([FromBody] BlukStatus data)
        {
            var blukResult = new BlukResult();
            foreach (var item in data.Ids)
            {
                try
                {
                    var endpoint = _service.GetById(item);
                    var count = _service.SetTrack(data.Status, item);
                    endpoint.IsTrack = data.Status;
                    EndPointManager.UpdateOrAdd(endpoint);
                    blukResult.AddSuccess();
                }
                catch (Exception)
                {
                    blukResult.AddFailure(item, $"id为{item}的数据修改失败");
                    continue;
                }
            }
            if (blukResult.FailureCount > 0)        //如果上面失败，则采用补偿机制（所有接口全部重新加载）
            {
                EndPointManager.Clear();
                var list = _service.GetList();
                EndPointManager.Register(list);
            }

            return blukResult;
        }


    }
}
